package cn.tedu.tnt_sky.interceptor;

import cn.tedu.tnt_sky.common.context.BaseContext;
import cn.tedu.tnt_sky.common.response.JwtClaimsConstant;
import cn.tedu.tnt_sky.common.response.MessageConstant;
import cn.tedu.tnt_sky.common.utils.JwtUtils;
import cn.tedu.tnt_sky.exception.AccountExistsException;
import cn.tedu.tnt_sky.exception.AccountNotFoundException;
import cn.tedu.tnt_sky.exception.PasswordErrorException;
import cn.tedu.tnt_sky.exception.TokenException;
import cn.tedu.tnt_sky.mapper.admin.AdminMapper;
import cn.tedu.tnt_sky.pojo.entity.Admin;
import cn.tedu.tnt_sky.service.AdminService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    AdminMapper adminMapper;


    /**
     * 进入controller方法之前执行。如果返回false，则不会执行 controller 的方法
     */
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler){

        // 获取URI
        String URI = request.getRequestURI();
        log.info("当前拦截请求URI：{}",URI);

        // 判断   || URI.contains("/error")
        if (URI.contains("/tnt/admin/login")){
            log.info("放行");
            return true;
        }
        String token = request.getHeader("token");

        if (!StringUtils.hasLength(token)){
            log.error("token为空");
            throw new TokenException(MessageConstant.NOT_LOGIN);
        }
        try{
            Claims claims = JwtUtils.parseJWT(token);
            String username = String.valueOf(claims.get(JwtClaimsConstant.USERNAME).toString());
            log.info("当前管理员：{}", username);
            Long adminId = Long.valueOf(claims.get(JwtClaimsConstant.ADMIN_ID).toString());
            String password = String.valueOf(claims.get(JwtClaimsConstant.PASSWORD).toString());
            Admin admin = adminMapper.selectByUsername(username);
            if (admin == null) {
                throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
            }
            if (!username.equals(admin.getUsername())){
                throw new AccountExistsException(MessageConstant.NOT_LOGIN);
            }
            if (!password.equals(admin.getPassword())){
                throw new PasswordErrorException(MessageConstant.NOT_LOGIN);
            }
            BaseContext.setCurrentId(adminId);
            return true;
        }catch(ExpiredJwtException ex) {
            log.error("token已过期");
           throw new TokenException(MessageConstant.NOT_LOGIN);
        }
    }
}
